/**
 * Created by ljy on 2016/6/18.
 */
var http = require("http")
var fs = require("fs")
var path = require("path")
var _ = require("underscore")


var dirArray = []

var isFile = false

var sever = http.createServer()
sever.on("request",function (req, res) {
    var url = req.url
    //没有图标图片
    if(url === "/favicon.ico") return
    //处理首页
    if(url === "/"){
        //只要一进主页，路径数组刷新，防止多次进入主页时，路径混乱
        dirArray = [__dirname]
        readDirRender(dirArray,res)
    //处理返回上一级目录
    }else if(url === "/return"){
        //返回上一级目录
        //清空最近一次的路径记录，然后再读取路径
        dirArray.pop()
        readDirRender(dirArray,res)
    }else{
        //判断是文件还是文件夹
        try{
            isFile = fs.statSync(path.join(dirArray.join(""),url)).isFile()
        }catch (err){
            console.log(err.message)
        }
        if(isFile){
            //查看文件
            //当前路径加入文件名
            readFileRender(dirArray,res,url)

        }else{
            //查看文件夹
            //记录当前进入的路径
            dirArray.push(url)
            readDirRender(dirArray,res)
        }
    }
})

sever.listen("3000",function () {
    console.log("服务器")
})


function readDirRender(arr,res) {
    var dirArr  = fs.readdirSync(arr.join(""))
    fs.readFile("./moble.html","utf8",function (err,data) {
        if(err){
            res.end("<h1>404 Not Found</h1>")
        }
        var compiled = _.template(data)
        var htmlStr = compiled({arr:dirArr})
        res.end(htmlStr)
    })
}

function readFileRender(arr,res,url) {
    fs.readFile(path.join(arr.join(""),url),"utf8",function (err,data) {
        if(err){
            res.end("<h1>404 Not Found</h1>")
        }
        res.end(data)
    })
}










